package com.ppc.ugo.common.log;

import com.alibaba.fastjson.JSON;
import com.ppc.ugo.utils.HttpContextUtil;
import com.ppc.ugo.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class LogAspect {

    /**
     * 切点
     */
    @Pointcut("@annotation(com.ppc.ugo.common.log.LogAnnotation)")
    public void lpt() {
    }

    @Around("lpt()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = point.proceed();
        long time = System.currentTimeMillis() - start;

        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
        log.info("module:{}", logAnnotation.module());
        log.info("operation:{}", logAnnotation.operation());
        //请求的方法名
        String className = point.getTarget().getClass().getName();
        String methodName = methodSignature.getName();
        log.info("request method:{}", className + "." + methodName + "()");
        //请求参数
        Object[] args = point.getArgs();
        String params = JSON.toJSONString(args);
        log.info("params:{}", params);
        //获取request 设置IP地址
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        log.info("ip:{}", IpUtils.getIpAddr(request));

        log.info("execute time : {} ms", time);
        log.info("=====================log end================================");

        return result;
    }

}
